<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xs:planLine:add']"
          v-if="optType !== 'view'"
        >新增</el-button>
      </el-col>
<!--    <el-col :span="1.5">-->
<!--      <el-button-->
<!--        type="warning"-->
<!--        plain-->
<!--        icon="el-icon-download"-->
<!--        size="mini"-->
<!--        @click="handleExport"-->
<!--        v-hasPermi="['xs:planLine:export']"-->
<!--      >导出</el-button>-->
<!--    </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" v-if="optType !== 'view'"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="planLineList"
      border
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column label="产品物料编码" align="center" width="140" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" width="140" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="产品/物料" align="center" prop="itemOrProduct">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct"/>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
      <el-table-column label="单价" align="center" prop="unitPrice" fixed="right" />
      <el-table-column label="数量" align="center" prop="quantity" fixed="right"  />
      <el-table-column label="需求日期" width="100" align="center" prop="demandDate" fixed="right" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.demandDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" fixed="right"  />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        v-if="optType !== 'view'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xs:planLine:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xs:planLine:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改销售预测计划明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品物料编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请选择产品物料编码" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" />
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品物料名称" prop="itemName">
              <el-input v-model="form.itemName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品物料标识" prop="itemOrProduct">
              <dict-tag :options="dict.type.mes_item_product" :value="form.itemOrProduct"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                :min="0"
                :step="1"
                v-model="form.unitPrice"
                placeholder="请输入单价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                :min="1"
                :step="1"
                v-model="form.quantity"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="demandDate">
              <el-date-picker clearable
                              v-model="form.demandDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择需求日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlanLine,
  getPlanLine,
  delPlanLine,
  addPlanLine,
  updatePlanLine
} from "@/api/mes/xs/planLine";
import { getColumnsConfigKey } from "@/api/system/columnsconfig";
import ItemSelect from "@/components/itemSelect/single.vue";

export default {
  name: "PlanLine",
  dicts: ['mes_item_product'],
  components: { ItemSelect },
  props: {
    planId: null,
    planCode: null,
    optType: null,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售预测计划明细表格数据
      planLineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: this.planId,
        planCode: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        batchCode: null,
        quantity: null,
        unitPrice: null,
        totalAmount: null,
        demandDate: null,
        lineStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "产品物料编码不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        demandDate: [
          { required: true, message: "需求日期不能为空", trigger: "change" }
        ],
      },
      columnsConfig:[],

    };
  },
  created() {
    this.getList();
    this.getItemBase();
  },
  watch: {
    planId: function (newVal, oldVal) {
      if (newVal !== oldVal && newVal !== null) {
        this.queryParams.planId = newVal;
        this.getList();
      }
    },
    planCode: function (newVal, oldVal) {
      if (newVal !== oldVal && newVal !== null) {
        this.queryParams.planCode = newVal;
        this.getList();
      }
    },
    'form.unitPrice' : function () {
      this.handleTotalAmount();
    },
    'form.quantity' : function () {
      this.handleTotalAmount();
    },
  },
  methods: {
    /** 查询销售预测计划明细列表 */
    getList() {
      this.loading = true;
      listPlanLine(this.queryParams).then(response => {
        this.planLineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        planId: this.planId,
        planCode: this.planCode,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        batchCode: null,
        quantity: null,
        unitPrice: null,
        totalAmount: null,
        demandDate: null,
        lineStatus: "未生成",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售预测计划明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getPlanLine(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售预测计划明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updatePlanLine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlanLine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除销售预测计划明细编号为"' + lineIds + '"的数据项？').then(function() {
        return delPlanLine(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xs/planLine/export', {
        ...this.queryParams
      }, `planLine_${new Date().getTime()}.xlsx`)
    },
    /** 获取基础物料动态字段 **/
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    // 计算总金额
    handleTotalAmount() {
      this.form.totalAmount = parseFloat(Number(this.form.unitPrice * this.form.quantity).toFixed(2));
    },
    // 选择物料点击
    handleSelectProduct(){
      this.$refs.itemSelect.showFlag = true;
    },
    //物料选择弹出框
    onItemSelected(obj){
      if(obj !== undefined && obj !== null){
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
        this.form.itemOrProduct = obj.itemOrProduct;
        this.form.batchCode = obj.batchCode;
      }
    },
    // 列合计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'totalAmount') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev +curr;
              }else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          }else {
            sums[index] = '---';
          }
        }else {
          sums[index] = '';
        }
      });
      return sums;
    },

  }
};
</script>
